package com.service.aliyun.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyuncs.exceptions.ServerException;
import com.service.aliyun.IAliyunService;
import com.service.aliyun.ICdnService;
import com.service.aliyun.IOssService;
import com.utils.enums.ENUM_SUCESS;

/**
 * @author geliyang
 *
 */
@Service("aliyunService")
public class AliyunServiceImpl implements IAliyunService{
	
	@Autowired
	private IOssService ossService;
	
	@Autowired
	private ICdnService cdnService;
	
	@Override
	public Integer uploadAndRefresh(String path, Object obj) throws OSSException, ClientException, ServerException,Exception{
		Integer sucess = 0;
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentType("text/html");
		if(obj instanceof InputStream){
			meta.setContentLength(((InputStream) obj).available());
			sucess = ossService.OSSUpload(path, (InputStream)obj, meta);
		}else if(obj instanceof String){
			meta.setContentLength(((String) obj).length());
			sucess = ossService.OSSUpload(path, new ByteArrayInputStream(obj.toString().getBytes()), meta);
		}
		if(!ObjectUtils.isEmpty(sucess) && sucess.equals(ENUM_SUCESS.SUCESS.value)){
			cdnService.refreshObjectOfCdn(path);
		}
		return ENUM_SUCESS.SUCESS.value;
	}
	
	@Override
	public Integer upload(String path, Object obj) throws OSSException, ClientException, ServerException,Exception{
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentType("text/html");
		if(obj instanceof InputStream){
			meta.setContentLength(((InputStream) obj).available());
			ossService.OSSUpload(path, (InputStream)obj, meta);
		}else if(obj instanceof String){
			meta.setContentLength(((String) obj).length());
			ossService.OSSUpload(path, new ByteArrayInputStream(obj.toString().getBytes()), meta);
		}
		return ENUM_SUCESS.SUCESS.value;
	}

}
